<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.nickname"
        placeholder="渠道名"
        style="width: 100px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-option
        v-for="item in options"
        :key="item.channelId"
        :label="item.channel_name"
        :value="item.channelId"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="success"
        icon="el-icon-plus"
        @click="addSysApiKey"
      >
        新增
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="编号" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="系统接入名称"
        class-name="status-col"
        min-width="110"
      >
        <template slot-scope="{ row }">
          {{ row.tissueName }}
        </template>
      </el-table-column>
      <el-table-column
        label="系统接入编码"
        class-name="status-col"
        min-width="110"
      >
        <template slot-scope="{ row }">
          {{ row.systemCode }}
        </template>
      </el-table-column>
      <el-table-column
        label="权限"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          {{ row.authorityList }}
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-tag v-if="row.status == 'Y'">启用</el-tag>
          <el-tag v-if="row.status == 'N'" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="系统接入类型"
        class-name="status-col"
        min-width="100"
      >
        <template slot-scope="{ row }">
          {{ systemType[row.systemType] }}
        </template>
      </el-table-column>
      <el-table-column label="分润模式" class-name="status-col" min-width="100">
        <template slot-scope="{ row }">
          {{ shareProfit[row.shareProfit] }}
        </template>
      </el-table-column>
      <el-table-column label="扣量比例" class-name="status-col" min-width="100">
        <template slot-scope="{ row }">
          {{ row.deduction }}
        </template>
      </el-table-column>
      <el-table-column
        label="前置筛选配置"
        class-name="status-col"
        min-width="130"
      >
        <template slot-scope="{ row }">
          {{ row.preFilter }}
        </template>
      </el-table-column>
      <el-table-column label="备注" class-name="status-col" min-width="110">
        <template slot-scope="{ row }">
          {{ row.remark }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="310"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="changeStatus(row)">
            切换状态
          </el-button>
          <el-button
            v-if="row.state == 1"
            type="info"
            size="mini"
            @click="handleEdit(row, 0)"
          >
            禁用
          </el-button>
          <el-button
            v-if="row.state == 0"
            type="success"
            size="mini"
            @click="handleEdit(row, 1)"
          >
            启用
          </el-button>
          <!-- <el-button type="text" @click="dialogFormVisible = true">修改权限</el-button> -->
          <el-button type="primary" size="mini" @click="echoSysApiKey(row)">
            修改
          </el-button>
          <el-button size="mini" type="danger" @click="deleteSysApi(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getSysKey"
    />
    <!-- 新增系统密钥表单 -->
    <el-dialog
      :title="textMap[dialogStatus] + '系统密钥'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="sysForm"
        :model="sysApiKeyData"
        :rules="syRules"
        label-width="80px"
      >
        <el-form-item label="接入名称" prop="tissueName">
          <el-input v-model="sysApiKeyData.tissueName"></el-input>
        </el-form-item>
        <el-form-item label="接入编码" prop="systemCode">
          <el-input
            v-model="sysApiKeyData.systemCode"
            :disabled="dialogStatus == 'create' ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item label="接入密钥" v-if="dialogStatus == 'update'">
          <el-input v-model="sysApiKeyData.secretKey"></el-input>
        </el-form-item>
        <el-form-item label="接入类型" prop="systemType">
          <el-select
            v-model="sysApiKeyData.systemType"
            clearable
            class="filter-item"
          >
            <el-option value="AUTH_API" label="买量">买量</el-option>
            <el-option value="JOINT" label="联合登陆">联合登陆</el-option>
            <el-option value="FORM" label="表单">表单</el-option>
            <el-option value="NONE" label="渠道授信">渠道授信</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分润模式" prop="shareProfit">
          <el-select
            v-model="sysApiKeyData.shareProfit"
            clearable
            class="filter-item"
          >
            <el-option value="PRICE" label="单价">单价</el-option>
            <el-option value="SHARE" label="分润">分润</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="扣量比例" prop="deduction">
          <el-input v-model="sysApiKeyData.deduction"></el-input>
        </el-form-item>
        <el-form-item label="前置筛选配置" label-width="100px">
          <el-input v-model="sysApiKeyData.preFilter"></el-input>
        </el-form-item>
        <el-form-item
          label="是否开启授信API卖量"
          label-width="160px"
          prop="apiIsOpen"
        >
          <el-radio-group v-model="sysApiKeyData.apiIsOpen">
            <el-radio :label="true">
              开启
            </el-radio>
            <el-radio :label="false">
              关闭
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="接入权限" prop="authority">
          <el-checkbox-group v-model="sysApiKeyData.authority">
            <el-checkbox label="预匹配/撞库" name="collision"></el-checkbox>
            <el-checkbox label="进件推送" name="apply"></el-checkbox>
            <el-checkbox label="状态查询" name="queryApply"></el-checkbox>
            <el-checkbox label="联合登陆" name="unionLogin"></el-checkbox>
            <el-checkbox label="撞库查询" name="check"></el-checkbox>
            <el-checkbox label="导单" name="incoming"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="ip白名单" prop="white">
          <el-input
            type="textarea"
            v-model="sysApiKeyData.white"
            placeholder="请以逗号分隔"
          ></el-input>
        </el-form-item>
        <el-form-item label="回调地址">
          <el-input
            type="textarea"
            v-model="sysApiKeyData.callBack"
            placeholder="请输入回调地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="sysApiKeyData.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="dialogStatus == 'create' ? saveSysApiKey() : updateSysKey()"
            >立即{{ dialogStatus == 'create' ? '创建' : '修改' }}</el-button
          >
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  editState,
  deleteById,
  resetpwd,
  getSysKey,
  changeStatus,
  saveSysApiKey,
  deleteSysApi,
  getSysApiKeyById,
  updateSysKeyApi,
  createSign
} from '@/api/sysKey';
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
export default {
  name: 'Channellist',
  components: { Pagination },
  data() {
    return {
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 10,
        apk: '',
        nickname: '',
        username: ''
      },
      authorityList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      systemType: {
        AUTH_API: '买量',
        JOINT: '联合登陆',
        FORM: '表单',
        NONE: '渠道授信'
      },
      shareProfit: {
        PRICE: '单价',
        SHARE: '分润'
      },
      authority: {
        collision: '预匹配/撞库',
        apply: '进件推送',
        queryApply: '状态查询',
        unionLogin: '联合登陆',
        check: '撞库查询',
        incoming: '导单',
        fullAuthMatch: '全量MD5'
      },
      dialogPvVisible: false,
      downloadLoading: false,
      optionsCopy: [],
      options: [],
      listLoading: true,
      sysApiKeyData: {
        tissueName: '',
        systemCode: '',
        systemType: '',
        shareProfit: '',
        deduction: '',
        preFilter: '{}',
        apiIsOpen: true,
        authority: [],
        white: '',
        remark: '',
        callBack: ''
      },
      syRules: {
        tissueName: [
          { required: true, message: '请填写接入名称', trigger: 'blur' }
        ],
        systemCode: {
          required: true,
          message: '请填写接入类型',
          trigger: 'change'
        },
        systemType: {
          required: true,
          message: '请填写接入类型',
          trigger: 'change'
        },
        shareProfit: {
          required: true,
          message: '请填写分润模式',
          trigger: 'change'
        },
        deduction: [
          {
            required: true,
            message: '请填写扣量比例',
            trigger: 'blur'
          },
          {
            pattern: /^([1-9]|10)$/g,
            message: '请输入1-9',
            trigger: 'blur'
          }
        ],
        apiIsOpen: {
          required: true,
          message: '是否开启授信API卖量',
          trigger: 'blur'
        },
        authority: {
          required: true,
          message: '请选择接入权限',
          trigger: 'change'
        },
        white: { required: true, message: '请填写ip白名单', trigger: 'blur' }
      }
    };
  },
  created() {
    this.getSysKey(this.listQuery);
  },
  methods: {
    // 获取列表
    async getSysKey(listQuery) {
      const res = await getSysKey(this.listQuery);
      const newData = res.data.data.records.map(item => {
        if (item.authority) {
          const authorityList = item.authority.split(',');
          const newArr = authorityList.map(item => {
            return this.authority[item];
          });
          item.authorityList = newArr;
        } else {
          item.authorityList = '-';
        }

        return item;
      });
      this.tableData = newData;
      this.total = res.data.data.total;
      this.listLoading = false;
    },
    handleFilter() {
      this.listQuery.current = 1;
      if (this.listQuery.channelId === undefined) {
        this.getSysKey(this.listQuery);
      } else {
        this.options.forEach(element => {
          if (element.channelId === this.listQuery.channelId) {
            this.listQuery.nickname = element.channel_name;
            this.getSysKey(this.listQuery);
          }
        });
      }
    },
    async changeStatus(row) {
      const data = {
        status: row.status,
        id: row.id
      };
      const res = await changeStatus(data);
      if (res.data.code === 200) {
        this.$notify({
          title: '切换成功',
          message: '切换成功',
          type: 'success',
          duration: 2000
        });
        this.getSysKey(this.listQuery);
      } else {
        this.$notify({
          title: '切换失败',
          message: '切换失败',
          type: 'fail',
          duration: 2000
        });
      }
    },
    resetTemp() {
      this.sysApiKeyData = {
        tissueName: '',
        systemCode: '',
        systemType: '',
        shareProfit: '',
        deduction: '',
        preFilter: '{}',
        apiIsOpen: true,
        authority: [],
        white: '',
        remark: '',
        callBack: ''
      };
      // 刷新表单数据验证提示
      this.$nextTick(() => {
        this.$refs['sysForm'].clearValidate();
      });
    },
    handleEdit(row, statetype) {
      if (row.state === statetype) {
        this.$notify({
          title: '更新状态',
          message: '不能更改相同的状态',
          type: 'fail',
          duration: 2000
        });
      } else {
        editState({ id: row.id, state: statetype }).then(res => {
          if (res.data.code === 200) {
            this.$notify({
              title: '更新状态',
              message: '更新成功！',
              type: 'success',
              duration: 2000
            });
            this.getChannelList();
          } else {
            this.$notify({
              title: '更新状态',
              message: '更新失败！',
              type: 'fail',
              duration: 2000
            });
          }
        });
      }
    },
    handleDelete(row) {
      var that = this;
      this.$confirm('删除提示！', '确认删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        deleteById({ id: row.id }).then(res => {
          if (res.data.code === 200) {
            that.getChannelList();
          } else {
            this.$notify({
              title: '错误',
              message: res.data.msg,
              type: 'fail',
              duration: 2000
            });
          }
        });
      });
    },
    handleResetPwd(row) {
      resetpwd({ id: row.id }).then(res => {
        if (res.data.code === 200) {
          this.$notify({
            title: 'Success',
            message: res.data.msg,
            type: 'success',
            duration: 2000
          });
        } else {
          this.$notify({
            title: '错误',
            message: res.data.msg,
            type: 'fail',
            duration: 2000
          });
        }
      });
    },
    // 展示列表
    echoSysApiKey(row) {
      this.resetTemp();
      getSysApiKeyById(row.id).then(r => {
        this.sysApiKeyData = r.data.data;
        this.dialogFormVisible = true;
        this.dialogStatus = 'update';
      });
    },
    // 新增系统密钥
    addSysApiKey() {
      this.resetTemp();
      createSign({ data: new Date() }).then(res => {
        if (res.data.code === 200) {
          this.sysApiKeyData.systemCode = res.data.data;
          this.dialogStatus = 'create';
          this.dialogFormVisible = true;
        } else {
          this.$notify({
            title: '错误',
            message: '获取签名失败',
            type: 'fail',
            duration: 2000
          });
        }
      });
    },
    saveSysApiKey() {
      this.$refs['sysForm'].validate(valid => {
        if (valid) {
          saveSysApiKey(this.sysApiKeyData).then(r => {
            this.dialogFormVisible = false;
            this.$notify({
              title: '新增成功',
              message: '新增成功',
              type: 'success',
              duration: 1000
            });
            this.getSysKey(this.listQuery);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 删除SysKeyApi
    deleteSysApi(row) {
      deleteSysApi(row).then(r => {
        this.$notify({
          title: '删除成功',
          message: '删除成功',
          type: 'success',
          duration: 1000
        });
        this.getSysKey(this.listQuery);
      });
    },
    // 修改sysApiKey
    updateSysKey() {
      updateSysKeyApi(this.sysApiKeyData).then(r => {
        this.$notify({
          title: '修改成功',
          message: '修改成功',
          type: 'success',
          duration: 1000
        });
        this.dialogFormVisible = false;
        this.getSysKey(this.listQuery);
      });
    }
  }
};
</script>
